using Godot;
using System;
using GodotInk;
using System.Collections.Generic;
using Ink.Runtime;
using System.Runtime;

public partial class DialogView : WindowBase
{
	// Called when the node enters the scene tree for the first time.
	private InkStory story;
	private VBoxContainer textNode;
	private Label nameNode;
	private TextureRect iconNode;
	public override void addListener()
	{
		base.addListener();
		EventManager.getInstance().addListener(InkFuncEventType.INK_FUNC_EVENT_CHANGE_ACTOR, changeIconAndName);
	}

	public override void onShow()
	{
		base.onShow();
		//获取inkId
		object inkId = this.viewParamDict.GetValueOrDefault("InkId");
		if (inkId is not null)
		{


		}

		//获取ink文件
		List<ConfigInkInfo> configInk = ConfigManager.getInstance().findConfigByConditionInDb<ConfigInkInfo>("ConfigInkInfo", "id=3");
		GD.Print(configInk);
		this.story = ResourceLoader.Load<InkStory>("res://resouces/ink/" + configInk[0].fileName + ".ink");

		var kk = this.story.FetchVariable("player");
		GD.Print(kk);

		//Callable ccc = Callable.From((string name, object values) => this.showInkVarChange(name, values));
		//ccc.Call();
		//this.story.ObserveVariable()

		//Callable ccc = new Callable(this, MethodName.test);
		//this.story.ObserveVariable("ff", Callable.From<string, string>(this.showInkVarChange));

		StoryFuncTriggerManager.getInstance().setStoryListener(this.story);


		ContinueStory();
	}

	public override void init()
	{
		base.init();
		this.textNode = this.GetNode<VBoxContainer>("mainContainer/textContainer");
		this.iconNode = this.GetNode<TextureRect>("mainContainer/iconNameContainer/icon");
		this.nameNode = this.GetNode<Label>("mainContainer/iconNameContainer/name");

	}

	private void ContinueStory()
	{

		foreach (Node child in this.textNode.GetChildren())
			child.QueueFree();

		Label content = new() { Text = story.ContinueMaximally() };
		this.textNode.AddChild(content);

		foreach (InkChoice choice in story.CurrentChoices)
		{
			Button button = new() { Text = choice.Text };
			button.Pressed += delegate
			{
				story.ChooseChoiceIndex(choice.Index);
				ContinueStory();
			};
			this.textNode.AddChild(button);


		}
	}

	private void changeIconAndName(object k, EventParams f)
	{

		var roleId = (int)f.paramDict["roleId"];
		var resoucePath = ActorUtil.getActorResourcePath(ActorResourceType.HeadSprite, roleId);
		var actorConfig = ActorUtil.getActorBaseInfo(roleId);
		iconNode.Texture = GD.Load<Texture2D>(resoucePath);
		nameNode.Text = actorConfig.cName;

	}
}
